'use strict'

const fs = require('fs');

const path = require('path')

const router = require('koa-router')();

function filterFiles(dir){


    let files = fs.readdirSync(dir);

    let controllerFiles = files.filter(name=>{

        return name.endsWith('js')&&name !=='index.js'
    })
    return controllerFiles;
}

function registerRouter(files){

    files.forEach(element => {
        let tempFile = path.join(__dirname,element);

        let tmpRouters = require(tempFile);
        for(const key in tmpRouters){


            let type = tmpRouters[key][0];
            let fn = tmpRouters[key][1];

            if(type==='get'){

                router.get(key,fn)
            }else{

                router.post(key,fn)
            }
        }
    });

   
}


module.exports=function(){

    const dir = __dirname;
    const controllerFiles = filterFiles(dir);
    registerRouter(controllerFiles);
    return router.routes();
}

